<template>
  <l-layout class="l-tab-page" v-show="!lr_loadPage">
    <l-panel>
      <template #toolLeft>
        <l-query2
          :labelWidth="0"
          :popoverWidth="240"
          :items="queryItems"
          :formData="queryData"
          :loading="tableLoading"
          @search="handleSearch"
        >
          <template #type>
            <el-radio-group v-model="queryData.type" size="mini" @change="handleSearch">
              <el-radio-button label="2">未完成</el-radio-button>
              <el-radio-button label="1">完成</el-radio-button>
              <el-radio-button label="3">作废</el-radio-button>
            </el-radio-group>
          </template>
          <template #keyWord>
            <el-input v-model="queryData.keyWord" :placeholder="$t('请输入查询关键字')"></el-input>
          </template>
          <template #seachDate>
            <l-date
              format="yyyy-MM-dd"
              dateType="daterange"
              v-model="queryData.seachDate"
              startPlaceholder="开始时间"
              endPlaceholder="结束时间"
            >
            </l-date>
          </template>
        </l-query2>
      </template>
      <template #toolRight>
        <l-tool-btns :hasAdd="false">
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        ref="mainTable"
        :loading="tableLoading"
        :columns="columns"
        :dataSource="tableData"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <template v-slot:f_Title="scope">
          <el-button @click="handleLook(scope.row)" size="mini" type="text">{{ scope.row.f_Title }}</el-button>
        </template>
        <template v-slot:f_IsFinished="scope">
          <el-tag v-if="scope.row.f_EnabledMark == 3" size="mini" type="danger">作废</el-tag>
          <el-tag v-else-if="scope.row.f_IsFinished == 1" size="mini" type="warning">结束</el-tag>
          <el-tag v-else size="mini" type="success">运行中</el-tag>
        </template>
        <template v-slot:f_CreateDate="scope">
          {{ lr_dateFormat(scope.row.f_CreateDate) }}
        </template>
        <l-table-btns
          v-if="queryData.type != 3"
          :isFixed="false"
          :filterBtns="filterBtns"
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>

    <look-form
      ref="form"
      type="lookmy"
      :params="{ processId: processId }"
      :isLoadFormData="true"
      :title="title"
      :visible.sync="visible"
    >
    </look-form>

    <l-dialog
      :title="`${$t('指派审核人')}【${title}】`"
      :visible.sync="pointVisible"
      :width="500"
      :height="400"
      @ok="handlePointSave"
      @closed="handlePointCloseForm"
      @opened="handlePointOpenForm"
    >
      <point-form ref="PointForm" :nodeList="nodeList"></point-form>
    </l-dialog>
  </l-layout>
</template>

<script>
import LookForm from "./look.vue";
import PointForm from "./point.vue";
const api = window.$api.workflow.process;
export default {
  components: {
    LookForm,
    PointForm,
  },
  data() {
    return {
      lr_isPage: true,

      queryItems: [
        { prop: "type", span: 24 },
        { prop: "seachDate", span: 24 },
        { prop: "keyWord", span: 24 },
      ],
      queryData: {
        type: "2",
        keyWord: "",
        seachDate: "",
      },
      // 表格参数
      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tableCurrentPage: 1,
      tablePageSize: 50,
      columns: [
        { label: "标题", prop: "f_Title", minWidth: 100, align: "left" },
        { label: "流程模版", prop: "f_SchemeName", minWidth: 60, align: "left" },
        { label: "状态", prop: "f_IsFinished", width: 72, align: "center" },
        { label: "提交人", prop: "f_UserId", width: 96, align: "left", dataType: "user" },
        { label: "提交时间", prop: "f_CreateDate", width: 160, align: "left" },
      ],
      tableBtns: [
        { prop: "Point", label: "指派审核人", width: 80 },
        { prop: "Delete", label: "作废" },
      ],

      processId: "",
      title: "",
      visible: false,

      pointVisible: false,
      nodeList: [],
    };
  },
  computed: {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.loadTableData();
    },
    handleSearch() {
      this.loadTableData();
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTableData(true);
    },
    async loadTableData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      const queryData = this.$deepClone(this.queryData);

      queryData.rows = this.tablePageSize;
      queryData.page = this.tableCurrentPage;
      queryData.sidx = "F_CreateDate DESC";

      const data = await this.$awaitWraper(api.getPage(queryData));
      if (data != null) {
        this.tableData = data.rows;
        this.tableTotal = data.records;
      } else {
        this.tableData = [];
      }
      this.tableLoading = false;
    },
    handleLook(row) {
      this.processId = row.f_Id;
      this.title = row.f_Title;
      this.visible = true;
    },
    handleDelete($index, row) {
      this.$confirm("是否作废此流程?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.deleteProcess(row.f_Id).then(() => {
            this.tableData.splice($index, 1);
            this.tableTotal--;
            this.$message({
              type: "success",
              message: "作废成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    filterBtns(row, btns) {
      if (row.f_IsFinished == 1) {
        return [{ prop: "Delete", label: "作废" }];
      } else {
        return btns;
      }
    },

    handlePoint($index, row) {
      this.processId = row.f_Id;
      this.title = row.f_Title;
      this.pointVisible = true;
    },
    async handlePointOpenForm(showLoading, hideLoading) {
      showLoading("加载流程信息...");

      const data = await this.$awaitWraper(api.get(this.processId));
      const nodeMap = {};
      data.tasks.forEach((task) => {
        if ([1, 3, 5, 6].includes(task.f_Type)) {
          nodeMap[task.f_UnitId] = nodeMap[task.f_UnitId] || {
            unitId: task.f_UnitId,
            name: task.f_UnitName,
            userIds: [],
          };
          nodeMap[task.f_UnitId].userIds.push(task.f_UserId);
        }
      });
      const nodeList = [];
      for (let id in nodeMap) {
        nodeList.push(nodeMap[id]);
      }
      this.nodeList = nodeList;

      this.$refs.PointForm.setForm(nodeList);

      hideLoading();
    },
    handlePointCloseForm() {
      this.$refs.PointForm.resetForm();
    },
    async handlePointSave(showLoading, hideLoading) {
      const data = this.$refs.PointForm.getForm();
      const postData = {
        list: [],
      };

      for (let id in data) {
        postData.list.push({
          unitId: id,
          userIds: data[id],
        });
      }

      if (postData.list.length > 0) {
        showLoading("指派流程审核人...");
        const res = await this.$awaitWraper(api.pointProcess(this.processId, postData));
        if (res) {
          this.$message({
            type: "success",
            message: "指派审核人成功!",
          });
        }
        hideLoading();
      }

      this.pointVisible = false;
    },
  },
};
</script>
